//
//  HomeViewController.m
//  CarStore
//
//  Created by 千锋 on 16/1/25.
//  Copyright (c) 2016年 1000phone. All rights reserved.
//

#import "HomeViewController.h"
/** 表头*/
#import "HeaderReusableView.h"
#import "HomeScrollModel.h"
#import "HomePageModel.h"
#import "HomeCell.h"
#import "ScrollViewController.h"
#import "FirstHomeCell.h"
/** 跳转视图*/
#import "CarPriceTVController.h"
/** 详情界面*/
#import "DetailTVController.h"

/** 无数据界面*/
#import "NoDataViewController.h"

/** 网址链接*/
// 首页滚动视图的数据的网址
#define API_HOME_SCROLL @"http://api.cacaqc.com/zonghe/lunbotu"
// 首页其他表格视图的网址
#define API_HOME_OTHER @"http://api.cacaqc.com/car/HotCarInfoList"


@interface HomeViewController ()<SDCycleScrollViewDelegate,UICollectionViewDelegateFlowLayout,UICollectionViewDataSource>
/** 集合视图数据源*/
@property (nonatomic, strong) NSMutableArray *dataArray;
/** 滚动视图数据*/
@property (nonatomic, strong) NSMutableArray *scrollArray;
/** 集合视图*/
@property (nonatomic, strong) UICollectionView *collectionView;

@end

static NSString *scrollPath;
static NSString *otherPath;
@implementation HomeViewController

#pragma mark - 懒加载
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}
- (NSMutableArray *)scrollArray
{
    if (!_scrollArray) {
        _scrollArray = [NSMutableArray array];
    }
    return _scrollArray;
}

#pragma mark - 视图控制器加载
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    scrollPath = [DOCUMENT_PATH stringByAppendingPathComponent:@"scroll.plist"];
    otherPath = [DOCUMENT_PATH stringByAppendingString:@"other.plist"];
    // 创建UI
    [self createCollectionView];

    // 创建数据源
    [self setUpRefresh];
    [self.collectionView.mj_header beginRefreshing];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UI相关
/** 创建下拉刷新控件*/
- (void)setUpRefresh
{
    __weak typeof(self) weakSelf = self;
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 请求滚动视图上的数据
        [weakSelf requestData];
    }];
    self.collectionView.mj_header = header;
}
/** 创建UICollectionView*/
- (void)createCollectionView
{
    // 创建
    UICollectionViewFlowLayout *layout =[[UICollectionViewFlowLayout alloc]init];
    self.collectionView  =[[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
    // 设置属性
    layout.headerReferenceSize = CGSizeMake(0, 180);
    
    [self.view addSubview:self.collectionView];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    // 注册cell
    [self.collectionView registerNib:[UINib nibWithNibName:@"HomeCell" bundle:nil] forCellWithReuseIdentifier:@"HomeCellID"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"FirstHomeCell" bundle:nil] forCellWithReuseIdentifier:@"FirstHomeCellID"];
    // 注册表头
    [self.collectionView registerClass:[HeaderReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderReusableViewID"];
    // 设置代理
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsVerticalScrollIndicator = NO;
}

#pragma mark - 数据相关
/** 请求滚动视图的数据*/
- (void)requestData
{
    if (self.scrollArray.count == 0) {
        NSArray *scrolls = [NSArray arrayWithContentsOfFile:scrollPath];
        NSArray *others = [NSArray arrayWithContentsOfFile:otherPath];
        if (scrolls.count != 0&&others.count !=0) {
            [self addFromArray:scrolls isScroll:YES];
            [self addFromArray:others isScroll:NO];
            
        }else{
        __weak typeof(self) weakSelf = self;
        [AFHTTPSessionManager POST:API_HOME_SCROLL parmaeters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
            NSDictionary *body = responseObject[@"body"];
            NSArray *image_list = body[@"image_list"];
            [image_list writeToFile:scrollPath atomically:YES];
            
            [self addFromArray:image_list isScroll:YES];
            
            // 请求第二类数据
            [self requestDataArray];
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            [weakSelf endRefresh:NO status:@"网络不给力"];
        }];
        }
    }else if (self.dataArray.count == 0){
        // 请求第二类数据
        [self requestDataArray];
    }else{
        [self endRefresh:YES status:@"加载成功"];
    }
}
/** 请求集合视图的数据*/
- (void)requestDataArray
{
    if (self.dataArray.count == 0) {
        __weak typeof(self) weakSelf = self;
        [AFHTTPSessionManager POST:API_HOME_OTHER parmaeters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
            NSArray *body = responseObject[@"body"];
            
            [body writeToFile:otherPath atomically:YES];
            
            [self addFromArray:body isScroll:NO];
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            [weakSelf endRefresh:NO status:@"网络不给力"];
        }];
    }else{
        [self endRefresh:YES status:@"加载成功"];
    }
}
/** 装入数据源*/
- (void)addFromArray:(NSArray *)arr isScroll:(BOOL)isScroll
{
    if (isScroll) {
        for (NSDictionary * dic in arr) {
            HomeScrollModel *model = [HomeScrollModel modelWithDict:dic];
            [self.scrollArray addObject:model];
        }
    }else{
    for (NSDictionary *dic in arr) {
        HomePageModel *model = [HomePageModel modelWithDict:dic];
        [self.dataArray addObject:model];
    }
    [self endRefresh:YES status:@"加载成功"];
    // 刷新数据
    [self.collectionView reloadData];
    }
}

/** 结束刷新*/
- (void)endRefresh:(BOOL)isSuccess status:(NSString *)status
{
    [self.collectionView.mj_header endRefreshing];
    if (isSuccess) {
        [SVProgressHUD showSuccessWithStatus:status];
    }else{
        [SVProgressHUD showErrorWithStatus:status];
    }
}
#pragma mark - UICollectionViewDataSource
/** 视图个数*/
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.dataArray.count == 0)
        return 0;
    return self.dataArray.count + 1;
}
/** UICollectionViewCell的创建*/
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        FirstHomeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"FirstHomeCellID" forIndexPath:indexPath];
        // 添加四个按钮的点击事件
        NSArray *btns = @[cell.carPartBtn,cell.carPriceBtn,cell.carSafeBtn,cell.carImportBtn];
        for (FirstHomeBtn *btn in btns) {
            [btn addTarget:self action:@selector(benClicked:)];
        }
        return cell;
    }else{
        HomeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HomeCellID" forIndexPath:indexPath];
        HomePageModel *model = self.dataArray[indexPath.row - 1];
        cell.model = model;
        return cell;
    }
}
// 按钮点击事件
- (void)benClicked:(FirstHomeBtn *)sender
{
    switch (sender.tag) {
        case 101:{
            CarPriceTVController *tVC = [[CarPriceTVController alloc] init];
            [self.navigationController pushViewController:tVC animated:YES];
        }
            break;
        case 102:
            [self pushToNoDataVC];
            break;
        case 103:
            [self pushToNoDataVC];
            break;
        case 104:
            [self pushToNoDataVC];
            break;
        default:
            break;
    }
}
- (void)pushToNoDataVC
{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    
    NoDataViewController *noDataVC = [sb instantiateViewControllerWithIdentifier:@"NoDataViewController"];
    [self push:^{
       [self.navigationController pushViewController:noDataVC animated:YES];
    }];
}
// 隐藏控制栏
- (void)push:(void(^)(void))push
{
    self.hidesBottomBarWhenPushed = YES;
    push();
    self.hidesBottomBarWhenPushed = NO;
}

/** 设置组头*/
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    // 复用组头
    HeaderReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderReusableViewID" forIndexPath:indexPath];
    // 取出图片网址字符串
    NSMutableArray *imageUrls = @[].mutableCopy;
    for (HomeScrollModel *model in self.scrollArray) {
        [imageUrls addObject:model.image];
    }
    headerView.SDScrollView.delegate = self;
    headerView.imageUrls = imageUrls;
    return headerView;
}
/** 设置边距*/
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 5, 120, 5);
}
/** 设置cell大小*/
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return CGSizeMake(WITH - 10, 90);
    }else{
        return CGSizeMake(WITH/2 - 10, 200);
    }
}
#pragma mark - 选中回调
/** 选中回调*/
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    DetailTVController *detailVC = [[DetailTVController alloc] init];
    HomePageModel *model = self.dataArray[indexPath.row - 1];

    detailVC.model = model;
    
    [self push:^{
     [self.navigationController pushViewController:detailVC animated:YES];
    }];
}
#pragma mark -- SDCycleScrollViewDelegate
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    ScrollViewController *scrollVC = [[ScrollViewController alloc]init];
    scrollVC.model = self.scrollArray[index];
    [self push:^{
      [self.navigationController pushViewController:scrollVC animated:YES];
    }];
}

@end
